package com.mdd.front.controller;

import com.mdd.common.aop.NotLogin;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.MailUtil;
import com.mdd.common.util.RedisUtils;
import com.mdd.front.service.IUserService;
import com.mdd.front.vo.user.UserInfoVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author XYueong
 * @date 2023-12-04
 * @description: 邮件模块
 */
@Slf4j
@RestController
@RequestMapping("/api/mail")
@Api(tags = "邮件模块")
public class MailController {

    @Resource
    IUserService userService;

    @NotLogin
    @GetMapping("/sendRegisterCode")
    public AjaxResult sendCode(@RequestParam("username") String userName) {

        UserInfoVo userInfoVo = userService.infoByUserName(userName);
        if (userInfoVo!=null){
            throw new IllegalArgumentException("错误邮箱账号已经存在,请使用忘记密码找回");
        }


        if(!_isValidEmail(userName)){
            throw new IllegalArgumentException("邮箱格式不正确");
        }

        Object determineWhetherItAlreadyExists = RedisUtils.get("registerCode:lock:" + userName);
        if (determineWhetherItAlreadyExists != null) {
            throw new RuntimeException("请勿频繁发送邮件~");
        }
        String randomCode = _generateRandomCode(6);
        log.info("验证码生成:{}", randomCode);
        String htmlTemplate ="<!DOCTYPE html>\n" +
                "<html xmlns:th=\"http://www.thymeleaf.org\">\n" +
                "<head>\n" +
                "    <meta charset=\"utf-8\">\n" +
                "    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
                "    <meta name=\"description\" content=\"email code\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
                "</head>\n" +
                "<body>\n" +
                "<div style=\"background-color:#ECECEC; padding: 35px;\">\n" +
                "    <table cellpadding=\"0\" align=\"center\"\n" +
                "           style=\"width: 800px;height: 100%; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;\">\n" +
                "        <tbody>\n" +
                "        <tr>\n" +
                "            <th valign=\"middle\"\n" +
                "                style=\"height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: RGB(148,0,211); background-color: RGB(148,0,211); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;\">\n" +
                "                <font face=\"微软雅黑\" size=\"5\" style=\"color: rgb(255, 255, 255); \">欢迎您新来的勇者 WELCOME TO YOUR NEW BRAVE</font>\n" +
                "            </th>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td style=\"word-break:break-all\">\n" +
                "                <div style=\"padding:25px 35px 40px; background-color:#fff;opacity:0.8;\">\n" +
                "                    <h2 style=\"margin: 5px 0px; \">\n" +
                "                        <font color=\"#333333\" style=\"line-height: 20px; \">\n" +
                "                            <font style=\"line-height: 22px; \" size=\"4\">\n" +
                "                                尊敬的用户：</font>\n" +
                "                        </font>\n" +
                "                    </h2>\n" +
                "                    <!-- 中文 -->\n" +
                "                    <p>您好！感谢您注册勇者博客，您的账号正在进行邮箱验证，验证码为：<font color=\"#ff8c00\">"+randomCode+"</font>，有效期15分钟，请尽快填写验证码完成验证！</p><br>\n" +
                "                  \n" +
                "                    <div style=\"width:100%;margin:0 auto;\">\n" +
                "                        <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;text-align:right\">\n" +
                "                            <p>──薛之勇者</p>\n" +
                "                            <br>\n" +
                "                            <p>此为系统邮件，请勿回复<br>\n" +
                "                                Please do not reply to this system email\n" +
                "                            </p>\n" +
                "                            <!--<p>©xyueong</p>-->\n" +
                "                        </div>\n" +
                "                    </div>\n" +
                "                </div>\n" +
                "            </td>\n" +
                "        </tr>\n" +
                "        </tbody>\n" +
                "    </table>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>\n" +
                "\n" +
                "\n";
        //上锁
        RedisUtils.set("registerCode:lock:" + userName, randomCode, 60);
        //设置有效期
        RedisUtils.set("registerCode:" + userName, randomCode, 60*15);
        //异步发送邮件
        new Thread(() -> MailUtil.sendMail(userName,"勇者博客验证码",htmlTemplate)).start();

        return AjaxResult.success();
    }


    /**
     * 描述: 生成随机字符串
     *
     * @author: XYueong
     * @date: 2023/12/4
     */
    public static String _generateRandomCode(int length) {
        // 随机字符的范围
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder randomCode = new StringBuilder();

        // 使用Random类生成随机索引，并从字符集中获取字符
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            randomCode.append(characters.charAt(index));
        }

        return randomCode.toString();
    }



    /**
     * 描述: 校验邮箱
     * @author: XYueong
     * @date: 2023/12/4
     */
    public static boolean _isValidEmail(String email) {
        // 定义邮箱地址的正则表达式
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";

        Pattern pattern = Pattern.compile(emailRegex);
        Matcher matcher = pattern.matcher(email);

        return matcher.matches();
    }
}
